package com.wangjiang.mario.admin.common.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CopyUtil {

    private static Logger logger = LoggerFactory.getLogger(CopyUtil.class);

    /**
     * 复制对象
     *
     * @param src   原对象
     * @param clazz 对象类
     * @param <T>
     * @return 新的对象
     */
    public static <T> T copy(Object src, Class<T> clazz) {
        if (src == null) {
            return null;
        }
        T t = null;
        try {
            t = clazz.newInstance();
            BeanUtils.copyProperties(src, t);
            return t;
        } catch (Exception e) {
            logger.error("复制文件出错", e);
        }
        return t;
    }

    /**
     * 复制对象list集合
     *
     * @param srclist 原对象集合
     * @param clazz   对象类
     * @param <T>
     * @return 新的对象
     */
    public static <T> List<T> copyList(Object srclist, Class<T> clazz) {
        if (srclist == null) {
            return null;
        }
        List<T> destlist = new ArrayList<T>();
        List<Object> srcLists = (List<Object>) srclist;
        for (Object src : srcLists) {
            destlist.add(copy(src, clazz));
        }
        return destlist;
    }

    /**
     * target, 即将被覆盖的对象
     * src, 源对象
     * target中的null值将会被src中的字段覆盖
     */
    public static Object copyProperties(Object target, Object src) {
        // 获取target对象中的非空字段
        Field[] declaredFields = FieldUtils.getAllFields(target.getClass());

        List<String> ignoreProperties = new ArrayList<>();

        for (Field field : declaredFields) {
            //使其可以访问private
            try {
                field.setAccessible(true);
                if(field.get(target) != null) {
                    ignoreProperties.add(field.getName());
                }
                field.setAccessible(false);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        //转数组
        String[] propers = new String[ignoreProperties.size()];
        BeanUtils.copyProperties(src, target, ignoreProperties.toArray(propers));

        return target;
    }
}
